﻿using ErrorOr;
using Gym.Application.Common.Interfaces;
using Gym.Domain.SubscriptionAggregate;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gym.Application.Subscriptions.Commands.CreateSubscription
{
    public class CreateSubscriptionCommandHandler : IRequestHandler<CreateSubscriptionCommand, ErrorOr<Subscription>>
    {
        private readonly IAdminsRepository _adminsRepository;

        public CreateSubscriptionCommandHandler(IAdminsRepository adminsRepository)
        {
            _adminsRepository = adminsRepository;
        }

        public async Task<ErrorOr<Subscription>> Handle(CreateSubscriptionCommand request, CancellationToken cancellationToken)
        {
            var admin = await _adminsRepository.GetByIdAsync(request.AdminId);
            
            if (admin == null)
            {
                return Error.NotFound(description:"没有找到管理员信息");
            }

            if (admin.SubscriptionId is not null)
            {
                return Error.Conflict("管理员已有订阅信息");
            }

            var subscription = new Subscription(
                request.SubscriptionType,
                request.AdminId);
            admin.SetSubscription(subscription);

            await _adminsRepository.UpdateAsync(admin);
            return subscription;
        }
    }
}
